package com.liesheng.haylou.base;

import android.content.pm.PackageManager;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.liesheng.haylou.net.HttpCallback;
import com.liesheng.haylou.net.HttpService;
import com.liesheng.haylou.net.RetrofitFactory;
import com.liesheng.haylou.utils.ToastUtil;
import com.liesheng.haylou.view.dialog.ProgressBarDialog;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Date:2019/11/21
 * <p>
 * Author:wuzhiguang
 * <p>
 * Description:
 * 封装了一些常的方法
 */
public class BaseFunActivity extends AppCompatActivity implements IBaseFun {

    ArrayList<Subscription> subscriptions = new ArrayList<>();

    ProgressBarDialog progressBarDialog;

    @Override
    public <T extends BaseResult> void requestHttp(Observable<T> observable, final HttpCallback<T> callback) {
        Subscription subscription = observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<T>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onNext(T t) {
                        if (!t.isSuccess()) {
                            showToast(t.getMsg());
                            return;
                        }
                        if (callback != null)
                            callback.onNext(t);
                    }
                });

        addSubscription(subscription);
    }

    @Override
    public HttpService buildHttpService() {
        return RetrofitFactory.getHttpService();
    }

    @Override
    public void showToast(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    public void showToast(int strId) {
        ToastUtil.showToast(strId);
    }


    private PermissionListener mlistener;

    /**
     * 权限申请
     *
     * @param permissions 待申请的权限集合
     * @param listener    申请结果监听事件
     */
    @Override
    public void requestRunTimePermission(String[] permissions, PermissionListener listener) {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            listener.onGranted();
            return;
        }
        this.mlistener = listener;

        //用于存放为授权的权限
        List<String> permissionList = new ArrayList<>();
        //遍历传递过来的权限集合
        for (String permission : permissions) {
            //判断是否已经授权
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                //未授权，则加入待授权的权限集合中
                permissionList.add(permission);
            }
        }

        //判断集合
        if (!permissionList.isEmpty()) {  //如果集合不为空，则需要去授权
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {  //为空，则已经全部授权
            listener.onGranted();
        }
    }

    /**
     * 权限申请结果
     *
     * @param requestCode  请求码
     * @param permissions  所有的权限集合
     * @param grantResults 授权结果集合
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    //被用户拒绝的权限集合
                    List<String> deniedPermissions = new ArrayList<>();
                    //用户通过的权限集合
                    List<String> grantedPermissions = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        //获取授权结果，这是一个int类型的值
                        int grantResult = grantResults[i];

                        if (grantResult != PackageManager.PERMISSION_GRANTED) { //用户拒绝授权的权限
                            String permission = permissions[i];
                            deniedPermissions.add(permission);
                        } else {  //用户同意的权限
                            String permission = permissions[i];
                            grantedPermissions.add(permission);
                        }
                    }

                    if (deniedPermissions.isEmpty()) {  //用户拒绝权限为空
                        mlistener.onGranted();
                    } else {  //不为空
                        //回调授权成功的接口
                        mlistener.onDenied(deniedPermissions);
                        //回调授权失败的接口
                        mlistener.onGranted(grantedPermissions);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void showLoadingDialog() {
        if (progressBarDialog == null)
            progressBarDialog = new ProgressBarDialog();

        progressBarDialog.show(getSupportFragmentManager());
    }

    @Override
    public void showLoadingDialog(String msg) {
        if (progressBarDialog == null)
            progressBarDialog = new ProgressBarDialog();

        progressBarDialog.setMsg(msg).show(getSupportFragmentManager());
    }

    @Override
    public void dismissLoadingDialog() {
        if (progressBarDialog!=null)
            progressBarDialog.dismiss();
    }

    @Override
    public void addSubscription(Subscription subscription) {
        if (subscription != null) {
            subscriptions.add(subscription);
        }
    }

    @Override
    public void unsubscribe() {
        for (Subscription subscription : subscriptions) {
            if (subscription != null && !subscription.isUnsubscribed())
                subscription.unsubscribe();
        }
    }

    public String getStr(int rid) {
        return getResources().getString(rid);
    }

    public String getStr(int rid, Object... formatArgs) {
        return getResources().getString(rid, formatArgs);
    }
}
